package cz.muni.fi.xvano1.trinity.supplementary;

import cz.muni.fi.xvano1.trinity.core.Core;
import cz.muni.fi.xvano1.trinity.core.SecondaryParser;
import java.util.*;
import javax.servlet.ServletContextEvent;

/**
 * This class is used during initialization of web application and it stores
 * data for later use in global (application) scope.
 *
 * @author Jan Vano
 */
public class InitializationContextListener implements javax.servlet.ServletContextListener {

    /**
     * Attributes like list of available toolboxes, object which will hold
     * synchronization lock and others are initialized here.
     *
     * @param sce Servlet context event - event that servlet container pass to
     * this method
     */
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        Set<String> allowedKeys = SecondaryParser.getToolboxNames(Core.toolboxDirectory);
        sce.getServletContext().setAttribute("allowedKeys", transform(allowedKeys));
        List<Integer> yearList = DataSupplier.staticGetYears();
        sce.getServletContext().setAttribute("yearList", yearList);
        List<String> admins = DataSupplier.getAdmins();
        sce.getServletContext().setAttribute("admins", admins);
        List<String> locations = DataSupplier.staticGetLocations();
        sce.getServletContext().setAttribute("locations", locations);
        sce.getServletContext().setAttribute("calendar", new Object());
        sce.getServletContext().setAttribute("userAccessSync", new Object());
        Map<String, String[]> userAccess = new HashMap<String, String[]>();
        sce.getServletContext().setAttribute("userAccess", userAccess);


    }

    private List<String> transform(Set<String> keys) {
        List<String> result = new ArrayList<String>();
        if (keys != null) {
            if (keys.contains("MATLAB")) {
                keys.remove("MATLAB");
                result.add("MATLAB");
            }
            if (keys.contains("SIMULINK")) {
                keys.remove("SIMULINK");
                result.add("SIMULINK");
            }
            result.addAll(keys);
        }
        return result;
    }

    /**
     * This method is unused.
     *
     * @param sce Servlet context event - event that servlet container pass to
     * this method
     */
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
    }
}
